package br.com.sgi.type;



import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.usertype.UserType;
public class SimNaoType implements UserType{

	@Override
	public Object assemble(Serializable cached, Object value)
			throws HibernateException {
		return cached;
	}

	@Override
	public Object deepCopy(Object value) throws HibernateException {
		return value;
	}

	@Override
	public Serializable disassemble(Object value) throws HibernateException {
		return (Serializable) value;
	}

	@Override
	public boolean equals(Object x, Object y) throws HibernateException {
		if (x == y) return true;
		if (x == null || y == null) return false;
		return x.equals(y);
	}

	@Override
	public int hashCode(Object x) throws HibernateException {
		return x.hashCode();
	}

	@Override
	public boolean isMutable() {
		return false;
	}

	@Override
	public Object nullSafeGet(ResultSet resultSet, String[] names, Object owner)
			throws HibernateException, SQLException {

		String value = resultSet.getString(names[0]);
		if (resultSet.wasNull()) 
			return null;
				
		Boolean retVal = value == null ? false : value.equalsIgnoreCase("S") ? true : false;
		return retVal;
	}

	@Override
	public void nullSafeSet(PreparedStatement statement, Object value, int index)
			throws HibernateException, SQLException {
		if (value == null){
			statement.setNull(index, Hibernate.STRING.sqlType());
		}else{
			Boolean setVal = (Boolean) value;
			statement.setString(index, setVal ? "S" : "N");
		}
	}

	@Override
	public Object replace(Object original, Object target, Object owner)
			throws HibernateException {
		return original;
	}

	@Override
	@SuppressWarnings("unchecked")
	public Class returnedClass() {
		return Boolean.class;
	}

	@Override
	public int[] sqlTypes() {
		return new int[]{ Hibernate.STRING.sqlType() };
	}
}
